<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <TopSearch
          @searchListByCommand="searchListByCommand"
          @reload="reload"
        ></TopSearch>
        <el-alert :title="title" type="info" show-icon :closable="false">
        </el-alert>
        <!-- 展示表格 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="number" label="试题编号"></el-table-column>
          <el-table-column prop="subject" label="学科"></el-table-column>
          <el-table-column prop="catalog" label="目录"></el-table-column>
          <el-table-column prop="questionType" label="题型">
            <template #default="{ row }">
              {{ turnChoose(row) }}
            </template>
          </el-table-column>
          <el-table-column prop="question" label="题干">
            <template #default="{ row }">
              {{ turnString(row) }}
            </template>
          </el-table-column>
          <el-table-column prop="addDate" label="录入时间">
            <template #default="{ row }">
              {{ formatTime(row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="difficulty"
            label="难度"
            :formatter="difficultyFormatter"
          ></el-table-column>
          <el-table-column prop="creator" label="录入人"></el-table-column>
          <el-table-column label="操作" width="200px">
            <template #default="{ row }">
              <el-button
                type="primary"
                icon="el-icon-view"
                circle
                plain
                @click="previewExam(row)"
              ></el-button>
              <el-button
                type="success"
                icon="el-icon-edit"
                circle
                plain
                @click="$router.push(`/questions/new?id=${row.id}`)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                plain
                @click="delRow(row)"
              ></el-button>
              <el-button
                type="warning"
                icon="el-icon-check"
                circle
                plain
                @click="isPerfectMethods(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->

        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[2, 4, 6, 8, 10]"
            :page-size="pagesize"
            layout="prev, pager, next,sizes, jumper"
            :total="total"
            background
          >
          </el-pagination>
        </div>
      </el-card>

      <!-- 预览的dialog -->
      <PreviewDialog
        :showPreview.sync="showPreview"
        :previewRowData.sync="previewRowData"
        :reduceTagQuestion="reduceTagQuestion"
        :reduceTagAnswer="reduceTagAnswer"
      ></PreviewDialog>
    </div>
  </div>
</template>

<script>
import TopSearch from '../components/top-search.vue'
import PreviewDialog from '../components/questions-preview.vue'
import { list, remove, detail, choiceAdd } from '../../api/hmmm/questions'
import dayjs from 'dayjs'
export default {
  name: 'questions',
  components: {
    TopSearch,
    PreviewDialog
  },
  data () {
    return {
      tableData: [],
      showPreview: false, // 预览的dialog的显现与否
      previewRowData: {},
      reduceTagQuestion: '', // 传过去的dialog题干
      directoryName: '', // 传过去的dialog方向名
      reduceTagAnswer: '', // 传过去的dialog解析
      page: 1,
      pagesize: 2,
      total: 0
    }
  },
  created () {
    this.getBaseProblemList()
  },
  computed: {
    title () {
      return `数据一共${this.total}条`
    }
  },
  methods: {
    handleCurrentChange (curpage) {
      this.page = curpage
      this.getBaseProblemList()
    },
    handleSizeChange (pagesize) {
      this.pagesize = pagesize
      this.page = 1
      this.getBaseProblemList()
    },
    // 基础题库列表
    async getBaseProblemList () {
      const res = await list({ page: this.page, pagesize: this.pagesize })
      // const res1 = await list({ page: this.page, pagesize: 9999999999999999 })
      // console.log(res, '基础题库列表')
      this.tableData = res.data.items
      // if (res.data.items.length <= 0 && this.page > 1) {
      //   this.page--
      // }
      this.total = res.data.counts
    },
    // 题干转成字符串
    turnString (row) {
      return row.question.replace(/<[^>]+>/gi, '')
    },
    // 将1、2转成多选还是单选
    turnChoose (row) {
      if (Number(row.questionType) === 1) {
        return '单选'
      } else if (Number(row.questionType) === 2) {
        return '多选'
      } else {
        return '简答'
      }
    },
    // 处理时间
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD HH:MM:ss')
    },
    // 表格中难度数字传换成字符串
    difficultyFormatter (row) {
      const diff = +row.difficulty

      let x = ''
      switch (diff) {
        case 1:
          x = '简单'
          break
        case 2:
          x = '一般'
          break
        case 3:
          x = '困难'
          break
      }
      return x
    },
    // 删除列表某一项
    delRow (row) {
      this.$confirm('此操作将永久删除该题目,是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          if (this.tableData.length <= 1 && this.page > 1) {
            this.page--
          }
          await remove(row)
          this.getBaseProblemList()
          this.$message('删除成功!')
        })
        .catch(() => {
          this.$message('已取消删除')
        })
    },
    async previewExam (row) {
      this.showPreview = true
      const id = {}
      id.id = row.id
      const res = await detail(id)
      // console.log(res, '1111111111111111111119999999999999999999999999')
      this.previewRowData = { ...res.data }

      // this.previewRowData = { ...row }

      this.reduceTagQuestion = res.data.question.replace(/<[^>]+>/gi, '')
      this.reduceTagAnswer = res.data.answer.replace(/<[^>]+>/gi, '')
      // // 获取目录列表进行转换来回显
      // const res = await directorysList({ page: 1, pagesize: 99999999 })
      // // console.log(res, '11111111111111111111111111111111111')
      // console.log(row.id)
      // console.log(res.data.items)
      // console.log(res.data.items.find((item) => item.id === +row.id), '1111111111111')
      // this.directoryName = res.data.items.find((item) => item.id === +row.id).directoryName
    },
    // 是否精选
    isPerfectMethods (row) {
      console.log(row)
      this.$confirm('此操作将该题目加入精选, 是否继续?', '提示', {
        type: 'info'
      }).then(async () => {
        const obj = { ...row, choiceState: 1 }
        await choiceAdd(obj)
        this.$message.success('加入精选成功!')
        this.getBaseProblemList()
        this.$router.push('/questions/choice')
      })
    },
    // 通知父组件按照需求获取基础题库列表
    async searchListByCommand (obj) {
      const res = await list({ ...obj, page: 1, pagesize: this.pagesize })
      // console.log(res, '按照需求获取基础题库列表')
      this.tableData = res.data.items
      this.total = res.data.counts
    },
    // 清除完之后，重新获取下方列表
    reload () {
      this.getBaseProblemList()
    }
  }
}
</script>

<style lang='scss' scoped>
::v-deep {
  .pagination {
    text-align: right;
    margin-top: 20px;
  }
}
</style>
